package com.netty.io.chatroom;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangbq
 * @since 2020-12-04 20:47
 **/
public class GroupChatClient {
    private final String HOST = "localhost";
    private final Integer PORT = 6667;
    private SocketChannel socketChannel;
    private Selector selector;
    private String username;

    public GroupChatClient() throws IOException {
        //初始化工作
        this.selector = Selector.open();
        //连接服务器
        this.socketChannel = SocketChannel.open(new InetSocketAddress(HOST,PORT));
        //异步配置
        socketChannel.configureBlocking(false);
        socketChannel.register(selector, SelectionKey.OP_READ);
        this.username = socketChannel.getLocalAddress().toString().substring(1);
        System.out.println("当前连接 username ： " + username + " is  Ok");
    }

    public void sendDate(String msg){
        String info = "我是客户端 " + username + " 说 :" + "\t" + msg;
        ByteBuffer buffer = ByteBuffer.wrap(info.getBytes());
        try {
            socketChannel.write(buffer);
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("客户端请求发送失败 : " + e.getMessage());
        }
    }

    public void readInfo(){
        try {
            int selectCount = selector.select();
            //代表有可用的连接
            if (selectCount > 0) {
                Set<SelectionKey> selectionKeys = selector.keys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey next = iterator.next();
                    if (next.isReadable()){
                        //拿到通道，读取出来就可以了
                        SocketChannel channel = (SocketChannel) next.channel();
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        channel.read(byteBuffer);
                        //数据已经到了缓冲区，取出来然后序列化就可以了
                        String infoMsg = new String(byteBuffer.array());
                        System.out.println("获取到来自服务端的消息数据 ： " + infoMsg);
                    }
                }
            }else {
                System.out.println("没有可供客户端使用的通道");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        GroupChatClient groupChatClient = new GroupChatClient();
        new Thread(()-> {
            while (true) {
                groupChatClient.readInfo();
                try {
                    TimeUnit.SECONDS.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        //发送数据给服务端
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()){
            String line = scanner.nextLine();
            groupChatClient.sendDate(line);
        }
    }
}
